package pcbeonjms;

import java.util.ArrayList;
import javax.annotation.Resource;
import javax.jms.*;

/**
 *
 * @author bufu
 */
public class Main {

    @Resource(mappedName = "jms/ResourceConnection")
    private static TopicConnectionFactory m_connFactory;
    @Resource(mappedName = "jms/ProducersTopic")
    private static Topic m_topic;
    @Resource(mappedName = "jms/DinComertFactory")
    private static TopicConnectionFactory m_fDinComert;
    @Resource(mappedName = "jms/DinComertTopic")
    private static Topic m_tDinComert;
    @Resource(mappedName = "jms/ComertFactory")
    private static QueueConnectionFactory m_fComert;
    @Resource(mappedName = "jms/ComertQueue")
    private static Queue m_tComert;
    private static boolean debugMode = false;
    private ArrayList<Jucator> m_jucatori;
    private ArrayList<Producator> m_producatori;
    private Comert m_comert;

    public Main(int nrJucatori) throws JMSException {
        Cladire.populeazaCladiri();
        m_jucatori = new ArrayList<Jucator>();
        m_producatori = new ArrayList<Producator>();
        m_comert = new Comert(m_fDinComert, m_tDinComert, m_fComert, m_tComert);

        Producator producator;
        producator = new Producator(m_connFactory, m_topic, Resursa.LEMN, 3, 3);

        m_producatori.add(producator);

        producator = new Producator(m_connFactory, m_topic, Resursa.LEMN, 1, 3);
        m_producatori.add(producator);

        producator = new Producator(m_connFactory, m_topic, Resursa.PIATRA, 1, 1);
        m_producatori.add(producator);

        producator = new Producator(m_connFactory, m_topic, Resursa.PIATRA, 1, 3);
        m_producatori.add(producator);

        producator = new Producator(m_connFactory, m_topic, Resursa.METAL, 2, 2);
        m_producatori.add(producator);

        for (int i = 0; i < nrJucatori; i++) {
            m_jucatori.add(new Jucator(this, m_connFactory, m_topic, m_fComert,
                    m_tComert, m_fDinComert, m_tDinComert, "Jucator" + i));
        }
    }

    public void stopJoc() {
        for (Producator prod : m_producatori) {
            prod.interrupt();
        }
        for (Jucator juc : m_jucatori) {
            juc.stopPlayer();
        }
        m_comert.afiseazaStatisticile();
    }

    private void startJoc() {
        for (Producator prod : m_producatori) {
            prod.start();
        }
        for (Jucator juc : m_jucatori) {
            juc.start();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            Main joc = new Main(10);
            joc.startJoc();
        } catch (JMSException ex) {
            ex.printStackTrace(System.out);
        }
    }

    public static void debug(String str) {
        if (Main.debugMode) {
            System.out.println(str);
        }
    }
}
